<?php
/**
 * 生成地区JSON文件
 */
error_reporting(E_ALL);
ini_set('display_errors', 'On');
include_once("./includes/global.php");
include_once("./lib/Rpc.php");
set_time_limit(0);

if (RUN_ENV == 'produce' && !isLocalHostRequest()) { //是否是本机访问
    exit('非法操作');
}

//获取总行数
// $sql = "SELECT COUNT(*) AS `total` FROM `haiou_district`";
// $db->query($sql);
// $records = $db->fetchRow();
// $total = $records['total'];

//开始生成json文件
$fileName = './cache/district.json';

//清空文件
if (!file_exists($fileName)) {
    touch($fileName);
}

$arr = getDistrictItems(0,1);

$content = json_encode($arr,JSON_UNESCAPED_UNICODE);

file_put_contents($fileName, $content);

exit('OK');

/**
 * 获取列表
 * @param unknown $pid
 * @param unknown $level
 */
function getDistrictItems($pid, $level) {
    global $db;
    $sql = "SELECT `id`,`pid`,`name` FROM `haiou_district` WHERE pid = {$pid}";
    $db->query($sql);
    $records = $db->getRows();
    $level ++;
    if ($level <= 3 ) {
        foreach ($records as $k => $v) {
            $records[$k]['sub'] = getDistrictItems($v['id'], $level);
        }
    }
    return $records;
}

file_put_contents($fileName, ']');